import React from 'react';
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx';
import { WeaUpload, WeaNewScroll, WeaLocaleProvider } from 'ecCom';
import { Button, Icon, Progress, Popconfirm, Tooltip } from 'antd';
import '../../style/transportList.less';
import { getRandomString } from '../../../util';


const getLabel = WeaLocaleProvider.getLabel;


/*
* 属性：
*  uploadUrl
*  autoUpload
*  multiple       是否多文件上传 boolean
*  sliceable      是否允许分片 boolean
*  sliceSize      分片大小     number
*
*  onUploading
*
*
* 问题：
*  1.上传太猛会不会对服务器磁盘I/O造成影响？该如何调整？
*  2.最好计算文件哈希或摘要, 目测没有crypto-js
*
* */


// 替代组件库的上传组件，支持大文件分片上传、断点续传
@inject('transportStore')
@observer
class NativeUpload extends React.Component {
   static defaultProps = {
      uploadUrl: '',
      multiple: true,
      sliceable: false,
      sliceSize: 2 * 1024 * 1024,
   };

   constructor(props) {
      super(props);
      this.state = {
      };
      this.task = {}; // 用于记录上传的信息
   }

   // 点击选择文件
   clickSelect = (e) => {
 this.Input.click(); 
};

   // 文件选择完毕
   fileChange = (e) => {
      e.persist();
      const fileList = e.target.files;
      console.log('files', fileList);
   };

   // 开始上传
   startUpload = (e) => {
      const { sliceable, sliceSize } = this.props;
      const fileList = this.Input.files;

      for (let i = 0; i < fileList.length; i++) {
         sliceable && this.sliceUpload(fileList[i]);
         !sliceable && this.noSliceUpload(fileList[i]);
      }
   };

   // 没有分片的上传
   noSliceUpload = (file) => {};

   // 分片上传
   sliceUpload = (file) => {
      const { sliceSize } = this.props;
      const count = Math.ceil(file.size / sliceSize); // 分片数量
      const task = `${getRandomString(6)}-${new Date().getTime()}`; // 任务唯一标识，可以更换成文件哈希
      this.task[task] = { count, current: 0, send: 0 };
      for (let i = 0; i < count; i++) {
         let msg = { slice: true, task, name: file.name, count, current: i };
         let start = this.prev[task].send;
         let end = start + sliceSize;
         let blob = file.slice(start, end);
         let form = new FormData();
         form.append('msg', JSON.stringify(msg));
         form.append('file', blob); // 文件对象

         this.sendAjax(form, msg); // 发送ajax

         this.task[task] = { ...this.task[task], current: i, send: end };
         if (count === i + 1) {
            console.log('最后一个分片', msg);
         }
      }
   };

   // 发送ajax
   sendAjax = (form, msg) => {
      const { uploadUrl } = this.props;
      let xhr = new XMLHttpRequest();
      xhr.open('POST', uploadUrl, true);

      xhr.upload.addEventListener('loadstart', (e) => {
 this.xhrLoadStart(e, msg); 
});
      xhr.upload.addEventListener('progress', (e) => {
 this.xhrProgressHandle(e, msg); 
});
      xhr.upload.addEventListener('loadend', (e) => {
 this.xhrLoadEnd(e, msg); 
});
      xhr.addEventListener('load', (e) => {
 console.log('上传完成 onload'); 
});

      xhr.send(form);
   };

   // loadStart事件
   xhrLoadStart = (e, msg) => {
      msg.slice && (this.task[msg.task][msg.current] = { prevLoad: 0, prevTime: e.timeStamp });
      !msg.slice && (this.task[msg.task].self = { prevLoad: 0, prevTime: e.timeStamp });
   };

   // progress事件
   xhrProgressHandle = (e, msg) => {
      // 更新上传进度、上传速度、上传量
      const { onUploading } = this.props;
      const total = e.total,
load = e.loaded;
      let speed,
percent;
      percent = `${Math.round(e.loaded / e.total * 100)}%`;

      msg.slice && (speed = (load - this.task[msg.task][msg.current].prevLoad) / (e.timeStamp - this.task[msg.task][msg.current].prevTime));
      !msg.slice && (speed = (load - this.task[msg.task].self.prevLoad) / (e.timeStamp - this.task[msg.task].self.prevTime));
      // 转化speed速度单位
      switch (true) {
         case speed < 1024:
            speed = `${speed} B/S`;
            break;
         case speed >= 1024 && speed < 1024 * 1024:
            speed = `${(speed / 1024).toFixed(2)} KB/S`;
            break;
         case speed >= 1024 * 1024 && speed < 1024 * 1024 * 1024:
            speed = `${(speed / (1024 * 1024)).toFixed(2)} MB/S`;
            break;
         case speed >= 1024 * 1024 * 1024:
            speed = `${(speed / (1024 * 1024 * 1024)).toFixed(2)} GB/S`;
            break;
         default:
            speed = `${speed} B/S`;
            break;
      }

      const info = { total, load, speed, percent };
      typeof onUploading === 'function' && onUploading(info);
   };

   // loadend事件
   xhrLoadEnd = (e, msg) => {
      // delete this.task[msg.task][msg.current];
      console.log('上传完成 onloadend');
   };

   render() {
      const { multiple } = this.props;

      return (
         <div onClick={this.clickSelect}>
            { this.props.children }
            <div>
               <input type="file" ref={(e) => {
 this.Input = e; 
}} multiple={multiple} onChange={this.fileChange} />
            </div>
         </div>
      );
   }
}

export default NativeUpload;
